<template>
  <!-- <div class="dashboard-container"> -->
  <div class="app-container">
    <el-card class="page-tools">
      <el-col>
        <el-row type="flex" justify="end">
          <el-button
            type="warning"
            @click="showDialog = true"
            icon="el-icon-edit"
            size="small"
            >新增用户</el-button
          >
        </el-row>
      </el-col>

      <el-table
        :header-cell-style="{
          background: '#F9F7F9',
          color: '#606266',
          borderBottom: '2px solid #E2E2E2'
        }"
        style="margin-top: 50px"
        row-key="id"
        :data="treeList"
        default-expand-all
        :tree-props="{ hasChildren: 'hasChildren', children: 'children' }"
      >
        <el-table-column label="标题">
          <template slot-scope="scope">
            <i
              class="el-icon-folder-opened"
              v-if="!scope.row.children || scope.row.children.length == 0"
            ></i>
            <i
              class="el-icon-document-add"
              v-if="scope.row.children && scope.row.children.length > 0"
            ></i>
            <i class="el-icon-view" v-else></i>

            <span v-html="scope.row.title"></span>
          </template>
        </el-table-column>
        <el-table-column label="权限点代码" prop="code"> </el-table-column>

        <el-table-column label="操作" fixed="right" width="180px">
          <template slot-scope="{ row }">
            <!-- 编辑按钮 -->
            <el-button
              @click="editPermission(row.id)"
              type="primary"
              icon="el-icon-edit"
              circle
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              @click="deletePermission(row.id)"
              type="danger"
              icon="el-icon-delete"
              circle
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-row type="flex" justify="end" align="middle" style="height: 80px">
        <el-pagination
          prev-text="上一页"
          next-text="下一页"
          layout="prev, pager, sizes,next,jumper"
          :page-size.sync="page.pagesize"
          :current-page.sync="page.page"
          :total="total"
          :page-sizes="[10, 20, 30, 40]"
          @current-change="getEmployeeList"
          @size-change="getEmployeeList"
        />
      </el-row>
    </el-card>
    <!-- 新增用户权限弹层 -->
    <el-dialog
      :title="userId ? '创建菜单' : '修改菜单'"
      :visible.sync="showDialog"
      @close="closeDialog"
    >
      <!-- 表单 -->
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="权限组名称">
          <el-radio v-model="formData.radio" label="1">菜单</el-radio>
          <el-radio v-model="formData.radio" label="2">权限点</el-radio>
        </el-form-item>
        <el-form-item label="权限组名称" prop="permission_group">
          <cy-tree-select
            v-model="value"
            :data="treeList"
            style="width: 240px"
          ></cy-tree-select>
          <!-- <el-select v-model="value" placeholder="请选择">
            <el-option
              v-for="item in data"
              :key="item.id"
              :label="item.title"
              :value="item.code"
            >
              <el-tree
                :data="data"
                node-key="id"
                ref="tree"
                highlight-current
                :props="defaultProps"
                @check="save"
              >
              </el-tree>
            </el-option>
          </el-select> -->
          <!-- <el-tree
            :data="data"
            show-checkbox
            node-key="id"
            ref="tree"
            highlight-current
            :props="defaultProps"
            @check="save"
          >
          </el-tree> -->
        </el-form-item>
        <el-form-item label="权限代码" prop="code">
          <el-input
            v-model="formData.code"
            style="width: 80%"
            placeholder="请输入代码"
          />
        </el-form-item>
        <el-form-item label="权限标题" prop="title">
          <el-input
            v-model="formData.title"
            style="width: 80%"
            placeholder="请输入标题"
          />
        </el-form-item>
      </el-form>

      <!-- footer插槽 -->
      <template v-slot:footer>
        <el-row type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" @click="closeDialog">取消</el-button>
            <el-button type="primary" size="small" @click="addUser"
              >确定</el-button
            >
          </el-col>
        </el-row>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import CyTreeSelect from './TreeSelect.vue'

import { permissionList, add, detail, remove } from '@/api/base/permissions.js'
import { list as meausList } from '@/api/base/menus.js'
export default {
  components: { CyTreeSelect },
  data () {
    return {
      options: [
        {
          value: '选项1',
          label: '黄金糕'
        }
      ],
      value: '',
      radio: '1', // 菜单和权限点按钮的值
      Idlist: [],
      // 树形结构
      treeList: [
        {
          id: 28,
          pid: null,
          code: 'base',
          title: '后台框架',
          children: [
            {
              id: 29,
              pid: 28,
              code: 'base-users',
              title: '用户管理',
              children: [
                {
                  id: 44,
                  pid: 29,
                  code: 'base-users-add',
                  title: '用户新增',
                  is_point: true
                },
                {
                  id: 46,
                  pid: 29,
                  code: 'base-users-search',
                  title: '用户搜索',
                  is_point: true
                },
                {
                  id: 47,
                  pid: 29,
                  code: 'base-users-list',
                  title: '用户列表',
                  is_point: true
                },
                {
                  id: 48,
                  pid: 29,
                  code: 'base-users-paging',
                  title: '用户分页',
                  is_point: true
                }
              ]
            }
          ]
        }
      ],
      // defaultProps: {
      //   children: 'children',
      //   label: 'code'
      // },
      // 添加用户权限的弹层
      formData: {
        code: '',
        title: '',
        radio: 1,
        permissions: []
      },

      // value: '', // 当前选中选项的值
      // 校验规则
      rules: {
        code: [
          { required: true, message: '用户权限代码不能为空', trigger: 'blur' }
        ],
        title: [
          { required: true, message: '用户权限标题不能为空', trigger: 'blur' }
        ]
      },
      // 主界面数据
      userId: '',
      // defaultImg,
      showDialog: false,
      loading: false,
      tableData: [],
      page: {
        page: 1, // 当前页码
        pagesize: 20,
        title: ''
      },
      list: [],
      total: 0 // 总数
    }
  },
  created () {
    this.getPermissionList()
    this.getPermissions()
  },
  methods: {
    // 获取所有数据并转树形结构
    async getPermissions () {
      const { data } = await meausList()
      const newData = JSON.stringify(data).replace(/points/g, 'childs')
      // console.log(JSON.parse(newData))

      this.data[0].childs = JSON.parse(newData)
    },
    // 获取所有选中节点的id
    save () {
      const customerRangeId = this.$refs.tree
        .getCheckedNodes(true) // 组件自带
        .map((item) => {
          const json = {
            id: item.id
            // fullName: item.fullName
          }
          return json
        })
      const areaIdList = customerRangeId.map((item, index) => {
        return item.id
      })
      return areaIdList
    },
    // 清空搜索并重新请求所有的用户权限
    async getAllUserPermission () {
      this.page.title = ''
      this.getPermissionList()
    },
    // 搜索用户权限
    async searchUser () {
      if (this.page.title.trim() === '') return
      this.getPermissionList()
    },
    // 删除用户权限
    async deletePermission (id) {
      try {
        await this.$confirm('此操作将永久删除用户 , 是否继续?')
        const data = {
          id: id
        }
        await remove(data)
        this.$message.success('删除用户权限成功')
        this.getUserList()
      } catch (error) {
        console.log(error)
      }
    },
    //  编辑用户权限信息
    async editPermission (id) {
      this.userId = id
      this.showDialog = true
      const data = {
        id: this.userId
      }
      // 先进行数据的回显
      const res = await detail(data)
      console.log(res)
      this.formData.username = res.data.title
      this.formData.permissions = res.data.permissions
      // console.log(res.data.permissions)
      // this.$refs.tree.setCheckedKeys(this.formData.permissions, true)
      this.$refs.tree.setCheckedKeys(this.formData.permissions)

      // 点击确定相当于在一次发送添加新用户权限的功能
      // this.addUser(id)
    },
    // 获取当前选中的节点值
    getCheckedNodes (arg) {
      console.log(arg)
    },
    // 添加用户权限 或者 编辑用户权限（）
    async addUser () {
      this.Idlist = this.save()
      console.log(this.Idlist)
      const data = {
        title: this.formData.username,
        permissions: this.Idlist
      }
      this.$refs.tree.setCheckedKeys([])
      await add(data)
      this.getPermissionList()
      this.$message(`${this.userId}` ? '编辑用户权限成功' : '新增用户权限成功')
      this.closeDialog()
    },
    //  获取 用户权限列表
    async getPermissionList () {
      this.loading = true
      // const {
      //   data: { counts, list }
      // } = await meausList()
      const { data } = await meausList()
      const newData = JSON.stringify(data).replace(/points/g, 'children')
      const newData1 = newData.replace(/childs/g, 'children')
      // console.log(JSON.parse(newData))

      // this.data = JSON.parse(newData1)

      console.log(newData1)
      // this.total = counts
      // this.tableData = list
      // this.loading = false
    },
    // 关闭新增用户权限的弹层
    closeDialog () {
      this.showDialog = false
      this.formData = {
        username: '' // 用户权限姓名
      }
      this.$refs.formRef.resetFields()
    },
    getEmployeeList () {}
  }
}
</script>

<style scoped lang="scss">
.page-tools {
  margin: 10px 0;
  .record {
    line-height: 34px;
    i {
      margin-right: 5px;
      color: #919398;
    }
    display: inline-block;
    padding: 0px 10px;
    border-radius: 3px;
    background: #f4f4f4;
  }
}
</style>
